'''
处理频率相关的值，直接对数据进行处理
'''

from excutor.excutor import Excutor
import re

class Frequency(Excutor):

    def __init__(self,data):
        self.data = data
        self.frequency =  ['数字信号处理频率', '时钟频率',
                             '自谐振频率', '频率', '开关频率',
                              '工作频率', '输出频率', '采样频率', 
                              '测试频率', '增益带宽积', '带通',
                               '带阻', '带宽','频率公差']
        #找出字符串中的数
        self.patternNumbers = re.compile('\.[0-9]+|[0-9]+[.]?[0-9]*')
        #找到字符串中的Hz单位
        self.patternHZ = re.compile('[kKmMgG]Hz')

    

    #判断是否存在频率数据
    @staticmethod
    def Existence(data):
        frequency =  ['数字信号处理频率', '时钟频率',
                             '自谐振频率', '频率', '开关频率',
                              '工作频率', '输出频率', '采样频率', 
                              '测试频率', '增益带宽积', '带通',
                               '带阻', '带宽','频率公差']

        return data[data['new_key'].isin(frequency)]['new_key'].count()


    #修改数据表
    def processingData(self):
        for new_key in self.frequency:
            # 筛选出new_key对应的old_value数据
            old_values = self.data[self.data['new_key'] == new_key]\
                        ['old_value'] 
            #找到上述行的index值，以便存储数据
            indexOld_value = self.data[self.data['new_key'] == new_key].index
            new_values = []
            #频率种类过多，每种处理方式不同，分类多一些
            if new_key == '数字信号处理频率':
                #处理器
                for old_value in old_values:
                    new_value = self.changeValue1(old_value)
                    new_values.append(new_value)
            elif new_key == '时钟频率':
                #存储器
                for old_value in old_values:
                    new_value = self.changeValue2(old_value)
                    new_values.append(new_value)
            elif new_key ==  '自谐振频率':
                #电感
                for old_value in old_values:
                    new_value = self.changeValue3(old_value)
                    new_values.append(new_value)
            elif new_key == '增益带宽积':
                #放大器与比较器
                for old_value in old_values:
                    new_value = self.changeValue4(old_value)
                    new_values.append(new_value)
            elif new_key == '频率':
                #蜂鸣器,麦克风，射频滤波器，谐振器,振荡器
                for old_value in old_values:
                    new_value = self.changeValue5(old_value)
                    new_values.append(new_value)
            elif new_key == '开关频率':
                #光电传感器
                for old_value in old_values:
                    new_value = self.changeValue6(old_value)
                    new_values.append(new_value)
            elif new_key == '工作频率':
                #射频和同轴连接器，射频和微波，天线,微控制器
                for old_value in old_values:
                    new_value = self.changeValue7(old_value)
                    new_values.append(new_value)
            elif new_key == '带通':
                #射频滤波器
                for old_value in old_values:
                    new_value = self.changeValue8(old_value)
                    new_values.append(new_value)
            elif new_key == '带阻':
                #射频滤波器
                for old_value in old_values:
                    new_value = self.changeValue9(old_value)
                    new_values.append(new_value)
            elif new_key == '输出频率':
                #时钟和计时
                for old_value in old_values:
                    new_value = self.changeValue10(old_value)
                    new_values.append(new_value)
            elif new_key == '采样频率':
                #数据转换器
                for old_value in old_values:
                    new_value = self.changeValue11(old_value)
                    new_values.append(new_value)
            elif new_key == '测试频率':
                #天线
                for old_value in old_values:
                    new_value = self.changeValue12(old_value)
                    new_values.append(new_value)
            elif new_key == '频率公差':
                #谐振器，振荡器
                for old_value in old_values:
                    new_value = self.changeValue13(old_value)
                    new_values.append(new_value)
            elif new_key == '带宽':
                #运动传感器
                for old_value in old_values:
                    new_value = self.changeValue14(old_value)
                    new_values.append(new_value)

            self.data.loc[indexOld_value,'new_value_ref'] = new_values

            #将修改后的值写入数据
            #用loc方法可以用index索引查找特定多行 
            #self.data.loc[indexOld_value,'new_value_compare'] = new_values
        return self.data

    def changeValue1(self,old_value):
        #修改数字信号处理频率
        units = self.patternHZ.findall(old_value)
        return self.findNumAndSortThenReturn(old_value,units[0])

    def changeValue2(self,old_value):
        #修改时钟频率
        if 'ns' in old_value.lower() :
            #有ns
            if 'Hz' in old_value:
                #Hz和ns共存
                #将频率和秒拆分为两个字符串
                old_valueList = re.split('[kKmMgG]Hz',old_value)
                unitHz =self.patternHZ.findall(old_value)
                #频率
                strHz = self.findNumAndSortThenReturn(old_valueList[0],unitHz[0])
                #ns
                strns = self.findNumAndSortThenReturn(old_valueList[1],'ns')
                return strHz + ',' + strns
            else:
                #只有ns
                return self.findNumAndSortThenReturn(old_value,'ns')
        elif 'Hz' in old_value:
            #有Hz无ns
            unitHz = self.patternHZ.findall(old_value)
            return self.findNumAndSortThenReturn(old_value,unitHz[0])
        else:
            return old_value

    def changeValue3(self,old_value):
        #修改自谐振频率
        if 'hz' in old_value.lower():
            unitHz =self.patternHZ.findall(old_value)
            return self.findNumAndSortThenReturn(old_value,unitHz[0])
        else:
            return self.dropZero(old_value) + 'MHz'

    def changeValue4(self,old_value):
        #修改增益带宽积
        if 'db' in old_value.lower():
            return self.findNumAndSortThenReturn(old_value,'dB')
        else:
            old_value = self.unifiedUnit(old_value)
            units = self.patternHZ.findall(old_value)
            if units:
                return self.findNumAndSortThenReturn(old_value,units[0])
            else:
                return old_value

    def changeValue5(self,old_value):
        #修改频率
        numbers = re.findall('[0-9]+[,]?[0-9]*[.]?[0-9]*',old_value)
        numbers = self.dropComma(numbers)
        units = self.patternHZ.findall(old_value)
        if not numbers:
            return old_value
        numbers = self.sort(numbers)
        if len(numbers) == 1:
            if units:
                return numbers[0]+units[0]
            return numbers[0]+"MHz"
        if len(numbers) > 1:
            if len(numbers) == len(units):
                return numbers[0]  + ' to ' + numbers[-1] + units[-1]
            elif units:
                return numbers[0] + ' to ' + numbers[-1] + units[-1]
            return numbers[0] + ' to ' + numbers[-1] + "MHz"
   
    def changeValue6(self,old_value):
        #修改开关频率
        numbers = self.patternNumbers.findall(old_value)
        units = self.patternHZ.findall(old_value)
        if not numbers:
            return old_value
        numbers = self.sort(numbers)
        if len(numbers) == 1:
            if units:
                return numbers[0]+units[0]
            return numbers[0]+"MHz"
        if len(numbers) > 1:
            if len(numbers) == len(units):
                return numbers[0]  + ' to ' + numbers[-1] + units[-1]
            elif units:
                return numbers[0] + ' to ' + numbers[-1] + units[-1]
            return numbers[0] + ' to ' + numbers[-1] + "MHz"
   
    def changeValue7(self,old_value):
        #修改工作频率
        return self.changeValue6(old_value)
    
    def changeValue8(self,old_value):
        #修改带通
        return self.changeValue6(old_value)
    
    def changeValue9(self,old_value):
        #修改带阻
        numbers = self.patternNumbers.findall(old_value)
        units = self.patternHZ.findall(old_value)
        if 'DC' in old_value:
            if units:
                return 'DC' + ' to ' + numbers[-1] + units[-1]
            return 'DC' + ' to ' + numbers[-1] + 'MHz'
        else:
            return self.changeValue6(old_value)

    def changeValue10(self,old_value):
        #修改输出频率
        numbers = self.patternNumbers.findall(old_value)
        units = re.findall('[G]bps|[GgKkMm]Hz',old_value)

        if 'bps' not in old_value:
            return self.changeValue6(old_value)
        else:
            if len(numbers) == 1:
                return numbers[0] + units[0]
            elif len(numbers) > 1:
                if len(numbers) == len(units):
                    return numbers[0] + units[0] + ',' + numbers[-1] + units[-1]
                else:
                    return numbers[0] + ' to ' + numbers[-1] + units[0]
            else:
                return old_value

    def changeValue11(self,old_value):
        #修改采样频率
        numbers = self.patternNumbers.findall(old_value)
        units = re.findall('[GgKkMm]sps',old_value) 
        if not numbers:
            return old_value
        numbers = self.sort(numbers)
        if len(numbers) == 1:
            if units:
                return numbers[0]+units[0]
            return numbers[0]+"ksps"
        if len(numbers) > 1:
            if len(numbers) == len(units):
                return numbers[0]  + ' to ' + numbers[-1] + units[-1]
            elif units:
                return numbers[0] + ' to ' + numbers[-1] + units[-1]
            return numbers[0] + ' to ' + numbers[-1] + "ksps" 

    def changeValue12(self,old_value):
        #修改测试频率
        return self.changeValue6(old_value)
    
    def changeValue13(self,old_value):
        #修改频率公差
        numbers = re.findall('[±-]?[0-9]+[.]?[0-9]*',old_value)
        units = re.findall('[Pp]{2}[mMbB]|%',old_value)
        if not(numbers and units):
            return old_value
        elif len(numbers) == 1:
            return numbers[0] + units[0]
        elif len(numbers) > 1:
            return numbers[0] + ' to ' + numbers[-1] + units[0]
        else:
            return old_value

    def changeValue14(self,old_value):
        #修改带宽
        return self.changeValue6(old_value)
    
    def dropComma(self,numbers):
        #去掉数字中的逗号
        numbers = [x.replace(',','') for x in numbers]
        return numbers

    def sort(self,numStrList):
        #将字符串表示的数字转化为浮点数，并对list排序，之后再转化为字符串
        numFloatList = [float(x) for x in numStrList]
        numFloatList.sort()
        numStrList = [str(x) for x in numFloatList]
        return [self.dropZero(x) for x in numStrList]

    def dropZero(self,num):
        #将数字后无用的0舍去
        return re.split('(?=.)[.]?[0]+$',num)[0]

    def findNumAndSortThenReturn(self,old_value,unit):
        #找到old_value中的数字并排序
        numbers = self.patternNumbers.findall(old_value)
        numbers = self.sort(numbers)
        if len(numbers) == 1:
            return numbers[0] + unit
        elif len(numbers)>1:
            return numbers[0] + ' to ' + numbers[-1] + unit
        else:
            return old_value

    def unifiedUnit(self,old_value):
        #将频率单位统一为MHz
        units = self.patternHZ.findall(old_value)
        numbers = re.findall(r'[0-9]+[.]?[0-9]*(?=\s*[MmKkGg]*Hz)',old_value)
        if not numbers:
            return old_value
        elif len(numbers) == 1:
            return numbers[0] + units[0]
        else:
            for i in range(len(numbers)):
                if units[i].lower() == 'khz':
                    numbers[i] = str(float(numbers[i]) / 1000)
                elif units[i].lower() == 'ghz':
                    numbers[i] = str(float(numbers[i]) * 1000)
            numbers = list(set(numbers))
            return 'MHz'.join(numbers) + 'MHz'
            


    